import React from 'react';
import {Select, Spin} from 'antd';
import {SelectProps} from "rc-select/lib/Select";

// @ts-ignore
export default ({fetchOptions, debounceTimeout = 800, ...props}: & SelectProps) => {
  const [fetching, setFetching] = React.useState(false);
  const [options, setOptions] = React.useState(props.options);
  const fetchRef = React.useRef(0);
  const debounceFetcher = React.useMemo(() => {
    return (value: string) => {
      console.log(value);
      fetchRef.current += 1;
      const fetchId = fetchRef.current;
      setOptions([]);
      setFetching(true);
      fetchOptions(value).then((newOptions: React.SetStateAction<never[]>) => {
        if (fetchId !== fetchRef.current) {
          // for fetch callback order
          return;
        }
        // @ts-ignore
        setOptions(newOptions);
        setFetching(false);
      });
    };
  }, [fetchOptions, debounceTimeout]);

  const handleFocus = (e: any) => {
    debounceFetcher(e.target.value);
  };
  const onClear = () => {
    setOptions([]);
    debounceFetcher('');
  };

  return (  // @ts-ignore

    <Select
      allowClear={props.allowClear}
      labelInValue
      filterOption={false}
      onSearch={debounceFetcher}
      onClear={onClear}
      onFocus={handleFocus}
      notFoundContent={fetching ? <Spin size="small"/> : null}
      {...props}
      options={options}
    />
  );
};
